class UserController < ApplicationController
  layout "default"
  before_filter :check_login
  
  def login
    if request.post?
      user = User.authenticate(params[:user][:name], params[:user][:password])
      
      if user
        session[:user_id] = user.id
        # lets track some data
        user.login_count  = 0 if user.login_count.nil?
        user.login_count  = user.login_count + 1
        user.last_login   = Time.now
        user.status       = 1
        user.save!
        
        redirect_to :controller => :profile, :action => :show, :id => user.id
      else
        flash.now[:notice] = "Passwort falsch!"
      end
    end
  end
  
  def logout 
    # change status
    user = User.find(session[:user_id])
    user.status = 0
    user.save!
    
    session[:user_id] = nil
    redirect_to :controller => :index
  end
  
  def add_user
    @user = User.new(params[:user])
    @user.registration_date = Time.now
    
    if request.post? and @user.save
      flash[:notice] = "Ihre Registrierung war erfolgreich!"
      @user = User.new
      redirect_to :controller => :index, :action => :index
    end
    
    if request.xhr?
      render :action => :add_user, :layout => false
    end
  end
  
  def check_login
    if session[:user_id]
      @user = User.find_by_id(session[:user_id])
    else
      @user = nil
    end
  end
  
  def list
    perpage = 15;
    
    if request.xhr?
      page    = params[:page].to_i
      limit   = page * perpage
      offset  = limit - perpage
    end 
    @users = User.find(:all, :order   => 'last_login DESC', 
                             :limit   => limit || perpage,
                             :offset   => offset || 0)
    if request.xhr?
      render :update do |page|
        page.insert_html(:bottom, 'users', { :partial => 'user', 
                                            :collection => @users })
      end
    else
      render(:type => "rhtml")
    end
  end
end
